import { authManager } from './auth'

// 请求拦截器：自动添加token和刷新token
export const request = async (url: string, options: RequestInit = {}): Promise<Response> => {
  const validToken = await authManager.getValidAccessToken()
  
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers,
  }

  // 添加访问令牌到请求头
  if (validToken) {
    headers['Authorization'] = `Bearer ${validToken}`
  }

  const response = await fetch(url, {
    ...options,
    headers,
  })

  // 如果返回401，尝试刷新token后重试
  if (response.status === 401 && validToken) {
    const refreshed = await authManager.refreshAccessToken()
    if (refreshed) {
      // 重新获取token并重试请求
      const newToken = authManager.getAccessToken()
      if (newToken) {
        headers['Authorization'] = `Bearer ${newToken}`
        return fetch(url, {
          ...options,
          headers,
        })
      }
    } else {
      // 刷新失败，清除认证信息并跳转到登录页
      authManager.clearAuth()
      window.location.href = '/login'
    }
  }

  return response
}

// 便捷的请求方法
export const api = {
  get: (url: string, options?: RequestInit) => 
    request(url, { ...options, method: 'GET' }),
  
  post: (url: string, data?: any, options?: RequestInit) => 
    request(url, {
      ...options,
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined,
    }),
  
  put: (url: string, data?: any, options?: RequestInit) => 
    request(url, {
      ...options,
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
    }),
  
  delete: (url: string, options?: RequestInit) => 
    request(url, { ...options, method: 'DELETE' }),
}
